package com.laoxu.springboot.service;

import com.laoxu.springboot.bean.Employee;
import com.laoxu.springboot.mapper.EmployeeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.*;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

@CacheConfig(cacheNames = "emp") //在此处加上就不用在每个方法上加了
@Service
public class EmployeeService {
    @Autowired
    EmployeeMapper employeeMapper;

    @Cacheable(/*cacheNames = "emp"*//*,keyGenerator = "myKeyGenerator",key = "#id", condition = "#a0>1" , unless = "#a0==1"*/)
    public Employee getEmp(Integer id){
        System.out.println("查询"+id+"号员工");
        return employeeMapper.getEmpById(id);
    }

    /**
     * 在方法后調用， 同步更新缓存
     * @param employee
     * @return
     */
    @CachePut(/*cacheNames = "emp",*/ key="#result.id")
    public Employee updateEmp(Employee employee){
        System.out.println("更新员工："+employee);
        employeeMapper.updateEmp(employee);

        return employee;
    }

    /**
     * allEntries = true  删除所有emp缓存
     * beforeInvocation = true 无论方法是否成功 都会删掉缓存
     * @param id
     */
    @CacheEvict(/*value = "emp",*/ key = "#id")
    public void deleteEmp(Integer id){
        System.out.println("删除员工："+id);
    }

    @Caching(
            cacheable = {
                    @Cacheable(/*value = "emp",*/ key = "#lastName")
            },
            put = {
                    @CachePut(/*value = "emp",*/ key = "#result.id"),
                    @CachePut(/*value = "email",*/ key = "#result.email")
            }

    )
    public Employee getEmpByLastName(String lastName){
        return employeeMapper.getEmpByLastName(lastName);
    }
}
